/**
 * Copyright (c) 2018, Alex. All rights reserved.
 */
package com.oschina.bottle.poi;

import com.oschina.bottle.poi.exp.CsvExporter;
import com.oschina.bottle.poi.exp.ExcelExporter;
import com.oschina.bottle.poi.imp.CsvImporter;
import com.oschina.bottle.poi.imp.ExcelImporter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 统一调用工具类
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2018/1/26
 * @since 1.0
 */
public enum FileHandler {

    CSV(new CsvImporter(), new CsvExporter(), Arrays.asList("csv")),

    EXCEL(new ExcelImporter(), new ExcelExporter(), Arrays.asList("xls", "xlsx"));

    private Importer importer;
    private Exporter exporter;
    private List<String> suffix;

    FileHandler(Importer importer, Exporter exporter, List<String> suffix) {
        this.importer = importer;
        this.exporter = exporter;
        this.suffix = suffix;
    }

    /**
     * 文件导入
     *
     * @param fileInfo          封装的导入文件信息
     * @throws IOException      io异常
     */
    public static void reslove(FileInfo fileInfo) throws IOException {
        FileHandler handler = getHandler(fileInfo.getName());
        if(handler == null) {
            throw new RuntimeException("格式错误");
        }

        handler.importer.resolve(fileInfo);
    }

    /**
     * 文件导出
     *
     * @param fileInfo          封装的文件导出信息
     * @throws IOException      io异常
     */
    public static void export(FileInfo fileInfo) throws IOException {
        FileHandler handler = getHandler(fileInfo.getName());
        if(handler == null) {
            throw new RuntimeException("格式错误");
        }
        handler.exporter.export(fileInfo);
    }

    private static FileHandler getHandler(String fileName) {
        String suffix = getSuffix(fileName);

        for(FileHandler handler : values()) {
            if(handler.suffix.contains(suffix.toLowerCase())) {
                return handler;
            }
        }

        return null;
    }

    public static String getSuffix(String filePath) {
        if(filePath == null || filePath.length() < 2) {
            return filePath;
        }
        return filePath.substring(filePath.lastIndexOf(".") + 1);
    }
}
